package io.github.biezhi.elves.download;

import io.github.biezhi.elves.common.Constants;
import io.github.biezhi.elves.request.Request;
import io.github.biezhi.elves.response.Response;
import io.github.biezhi.elves.scheduler.Scheduler;
import io.github.biezhi.elves.selenium.QccSelenium;
import lombok.extern.slf4j.Slf4j;
import java.io.InputStream;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

/**
 * 下载器线程
 *
 * @author biezhi
 * @date 2018/1/11
 */
@Slf4j
public class Downloader implements Runnable {

    private final Scheduler scheduler;
    private final Request   request;

    public Downloader(Scheduler scheduler, Request request) {
        this.scheduler = scheduler;
        this.request = request;
    }

    @Override
    public void run() {
        log.debug("[{}] 开始请求", request.getUrl());
        io.github.biezhi.request.Request httpReq = null;
        if ("get".equalsIgnoreCase(request.method())) {
        	httpReq = io.github.biezhi.request.Request.get(request.getUrl());
        }
        if ("post".equalsIgnoreCase(request.method())) {
            httpReq = io.github.biezhi.request.Request.post(request.getUrl());
        }

        InputStream result = getHttpResult(httpReq);
        
        String requestUrl = request.getUrl();
        log.debug("[{}] 下载完毕", requestUrl);
        Response response = new Response(request, result);
        String responseBody = response.body().toString();
//        System.out.println(this.getClass() + ".run方法,response.body{{}}==>" + responseBody);
        
        String scriptRequestUrl = requestUrl.replace("http://www.qichacha.com/", "http://www.qichacha.com/index_verify?type=companysearch&back=/");
		String scriptStr = "<script>window.location.href='" + scriptRequestUrl +"';</script>";
		if(scriptStr.equals(responseBody)){
			Constants.QCC_PAQU_STATE = "1";
			QccSelenium.reloadQccCookie(scriptRequestUrl);
			result = getHttpResult(httpReq);
			response = new Response(request, result);
		}else{
	        Document doc = Jsoup.parse(responseBody);
			Elements normalLoginElements = doc.select("#normalLoginPanel");
			if(normalLoginElements!=null && normalLoginElements.size()>0){
				Constants.QCC_PAQU_STATE = "2";
				QccSelenium.reloadQccCookie(scriptRequestUrl);
				result = getHttpResult(httpReq);
				response = new Response(request, result);
//				System.out.println(this.getClass() + ".run方法，重新获取登录后cookie信息，再次调用方法,response.body{{}}==>" + responseBody);
			}
		}
        scheduler.addResponse(response);
    }

    private InputStream getHttpResult(io.github.biezhi.request.Request httpReq){
    	InputStream result;
    	if(!Constants.IS_PROXY){
        	//不用代理
	        result = httpReq
	        		.contentType(request.contentType()).headers(request.getHeaders())
	                .connectTimeout(request.getSpider().getConfig().timeout())
	                .readTimeout(request.getSpider().getConfig().timeout())
	                .stream();
        }else{
        	//使用代理
        	result = httpReq
        			.useProxy(Constants.PROXY_IP, Constants.PROXY_PORT)
	        		.contentType(request.contentType()).headers(request.getHeaders())
	                .connectTimeout(request.getSpider().getConfig().timeout())
	                .readTimeout(request.getSpider().getConfig().timeout())
	                .stream();
        }
    	return result;
    }
}